package com.wxw.jwt.uitls;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * @author wxw
 * @data 2021/8/30 00 :16
 * @description
 */
@Slf4j
@Component
public class JwtUtil {

    private static final String secret = "secret";

    /**
     * 创建token
     */
    public static String createToken(String username, Long time) throws UnsupportedEncodingException {

        long expiration = System.currentTimeMillis() + time;
        Date expireDate = new Date(expiration);
        log.info("时间：{}----------------------",expireDate);
        String token = JWT.create()
                .withClaim("sys_username", username)
                .withExpiresAt(expireDate)
                .sign(Algorithm.HMAC256(secret));
        log.info("用户：{} =====> token：{}", username, token);
        return token;
    }

    /**
     * 校验token是否正确
     */
    public static boolean verify(String token, String username) throws UnsupportedEncodingException, TokenExpiredException {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm)
                .withClaim("sys_username", username)
                .build();
        verifier.verify(token);
        return true;
    }

    /**
     * 解析token，获取用户名
     */
    public static String getUsername(String token) {
        DecodedJWT decode = JWT.decode(token);
        return decode.getClaim("sys_username").asString();
    }

    /**
     * 验证token是否失效
     *
     * @param token
     * @return true:过期   false:没过期
     */
    public static boolean isExpired(String token) {
        try {
            final Date expiration = getExpiration(token);
            return expiration.before(new Date());
        } catch (JWTDecodeException JWT) {
            return true;
        }
    }

    /**
     * 获取jwt失效时间
     */
    public static Date getExpiration(String token) {
        return    JWT.decode(token).getExpiresAt();
    }
}

